package com.lemon.cloud.extension.annotation;

import com.lemon.cloud.extension.ExtensionPointRepository;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author lemon
 * @return
 * @description
 * @date 2019-09-14 23:24
 */
@Component
public class ExtPointAnnotationBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Autowired
    private ExtensionPointRepository extensionPointRepository;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(ExtPoint.class)
                && com.lemon.cloud.extension.ExtensionPoint.class.isAssignableFrom(bean.getClass())) {
            this.registerExtensionPoint(bean);
        }

        return bean;
    }

    /**
     * @param bean
     * @return void
     * @description
     * @author lemon
     * @date 2019-09-14 23:24
     */
    private void registerExtensionPoint(Object bean) {
        Class extensionPointClass = bean.getClass();
        com.lemon.cloud.extension.ExtensionPoint extensionPoint = (com.lemon.cloud.extension.ExtensionPoint) this.applicationContext.getBean(extensionPointClass);
        ExtPoint extensionAnn = (ExtPoint) extensionPointClass.getDeclaredAnnotation(ExtPoint.class);
        this.extensionPointRepository.registered(extensionAnn, extensionPoint);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}